/**
 * Copyright 2016-present scrm
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.maiquan.scrm;

import android.app.Application;

import com.facebook.infer.annotation.Assertions;
import com.facebook.react.ReactApplication;
import org.wonday.aliyun.push.AliyunPushPackage;
import com.theweflex.react.WeChatPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.cmcewen.blurview.BlurViewPackage;
import com.RNRSA.RNRSAPackage;
import fnd.reactaes.reactaes.ReactAESPackage;
import com.rnfs.RNFSPackage;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.microsoft.codepush.react.CodePush;
import com.oblador.vectoricons.VectorIconsPackage;
import com.richardcao.exceptionsmanager.react.ExceptionsManager;
import com.tencent.bugly.crashreport.CrashReport;
import android.support.multidex.MultiDex;
// import com.maiquan.scrm.push.PushModule;
// import com.maiquan.scrm.push.PushPackage;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import android.content.Context;
import android.graphics.Color;

import android.app.NotificationChannel;
import android.app.NotificationManager;

import org.wonday.aliyun.push.AliyunPushPackage;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.HuaWeiRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.GcmRegister;


import android.os.Build;
import android.webkit.WebView;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Nullable;

public class MainApplication extends Application implements ReactApplication {

    @Override
    public void onCreate() {
        super.onCreate();
        SoLoader.init(this, /* native exopackage */ false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        if (!BuildConfig.DEBUG) {
            CrashReport.initCrashReport(getApplicationContext(), "91faa14050", false);
        }

        this.initCloudChannel(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

        @Override
        protected ReactInstanceManager createReactInstanceManager() {
            ReactInstanceManagerBuilder builder = ReactInstanceManager.builder()
                    .setApplication(getApplication())
                    .setJSMainModulePath(getJSMainModuleName())
                    .setUseDeveloperSupport(getUseDeveloperSupport())
                    .setRedBoxHandler(getRedBoxHandler())
                    .setUIImplementationProvider(getUIImplementationProvider())
                    .setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
                    .setNativeModuleCallExceptionHandler(
                    new ScrmNativeModuleCallExceptionHandler());

            for (ReactPackage reactPackage : getPackages()) {
                builder.addPackage(reactPackage);
            }

            String jsBundleFile = getJSBundleFile();
            if (jsBundleFile != null) {
                builder.setJSBundleFile(jsBundleFile);
            } else {
                builder.setBundleAssetName(Assertions.assertNotNull(getBundleAssetName()));
            }
            return builder.build();
        }

        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Nullable
        @Override
        protected String getJSBundleFile() {
            return CodePush.getJSBundleFile();
        }

        @Override
        protected String getJSMainModuleName() {
            return "index";
        }

        @Override
        protected List<ReactPackage> getPackages() {
            List<ReactPackage> packages = Arrays.asList(
                    new MainReactPackage(),
            new AliyunPushPackage(),
                    new BlurViewPackage(),
                    new RNRSAPackage(),
                    new ReactAESPackage(),
                    new RNFSPackage(),
                    new AndroidWebViewPackage(),
                    new WeChatPackage(),
                    new CodePush(BuildConfig.CODEPUSH_KEY, MainApplication.this, BuildConfig.DEBUG),
                    new RNDeviceInfo(),
                    // new PushPackage(),
                    new VectorIconsPackage());
            ArrayList<ReactPackage> packageList = new ArrayList<>(packages);
            if (!BuildConfig.DEBUG) {
                packageList.add(new ExceptionsManager());
            }
            return packageList;
        }
    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    private void initCloudChannel(final Context applicationContext) {

        // 创建notificaiton channel
        this.createNotificationChannel();
        PushServiceFactory.init(applicationContext);
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.setNotificationSmallIcon(R.mipmap.ic_launcher_s);//设置通知栏小图标， 需要自行添加
        pushService.register(applicationContext, "25169808", "182324a99eea90d8350b3b2586c2e644", new CommonCallback() {
          @Override
          public void onSuccess(String responnse) {
            // success
          }
          @Override
          public void onFailed(String code, String message) {
            // failed
          }
        });
    
        // 注册方法会自动判断是否支持小米系统推送，如不支持会跳过注册。
        MiPushRegister.register(applicationContext, "5341789043336", "KoVWy95VsFysNyb1UrfSfQ==");
        // 注册方法会自动判断是否支持华为系统推送，如不支持会跳过注册。
        HuaWeiRegister.register(applicationContext);
        // 接入FCM/GCM初始化推送
        GcmRegister.register(applicationContext, "send_id", "application_id"); 
      }
    
    
      private void createNotificationChannel() {
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
              NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
              // 通知渠道的id
              String id = "1";
              // 用户可以看到的通知渠道的名字.
              CharSequence name = "notification channel";
              // 用户可以看到的通知渠道的描述
              String description = "notification description";
              int importance = NotificationManager.IMPORTANCE_HIGH;
              NotificationChannel mChannel = new NotificationChannel(id, name, importance);
              // 配置通知渠道的属性
              mChannel.setDescription(description);
              // 设置通知出现时的闪灯（如果 android 设备支持的话）
              mChannel.enableLights(true);
              mChannel.setLightColor(Color.RED);
              // 设置通知出现时的震动（如果 android 设备支持的话）
              mChannel.enableVibration(true);
              mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
              //最后在notificationmanager中创建该通知渠道
              mNotificationManager.createNotificationChannel(mChannel);
          }
      }
      // 添加结束
}
